const fs = require('fs');

const folderPath = './origin'; // 文件夹路径

let accumulate = 0;
try {
  const files = fs.readdirSync(folderPath);
  const finalArr = [];

  files.forEach((file) => {
    const res = JSON.parse(fs.readFileSync(`${folderPath}/${file}`, 'utf-8')).map(item => ({ key: item.key, note: item.note, parentId: item.parentId, title: item.title }));
    finalArr.push(...res);
  });

  const topLevel = finalArr.filter((item) => item.parentId === "-1");
  for (const level of topLevel) {
    const provinceList = getListFromTop(level, finalArr);

    accumulate += provinceList.length;
    console.log(`curLength: ${provinceList.length}, total: ${accumulate}, final: ${finalArr.length}`);
    fs.writeFileSync(`./province/${level.title}.txt`, jsonToString(provinceList));
  }
} catch (err) {
  console.error('无法读取文件夹：', err);
}

function jsonToString(arr) {
  return arr.map(item => {
    return `${item.key},${item.title},${item.parentId},${item.note}`;
  }).join('\n');
}

function getListFromTop(topLevel, finalArr) {
  const list = finalArr.filter(item => item.key.startsWith(topLevel.key));

  list.sort((a, b) => a.key.length - b.key.length)
  return list;
}

